package com.juku2024.juku

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.Group
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.callback.OnEpisodeClickCallback
import com.juku2024.juku.callback.OnNoDoubleClickListener
import com.juku2024.juku.db.entity.VideoEntity
import com.juku2024.juku.dialog.VideoEpisodeDialog
import com.juku2024.juku.dialog.VideoSourceDialog
import com.juku2024.juku.model.PlayInfoResponse
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.viewmodel.VideoDetailViewModelNew
import com.juku2024.juku.widget.LoadingView
import com.rabbit.videoplayer.MixPlayerView
import com.rabbit.videoplayer.OnChangeEpisodeListener
import com.rabbit.videoplayer.listener.OnFullScreenStatusListener
import com.rabbit.videoplayer.listener.OnLoadUnlockAdListener
import com.rabbit.videoplayer.listener.OnVodCompleteListener
import com.rabbit.videoplayer.listener.player.OnPreparedListener
import com.wanban.adutils.callback.OnLoadAdCallback
import com.wanban.adutils.utils.VideoInterstitialAdTools


class VideoPlayerSkitsActivity: BaseActivity(), OnNoDoubleClickListener {

    companion object {
        fun toPlayerActivity(context: Context, id: Long, name: String?, pic: String?){
            val intent = Intent(context, VideoPlayerSkitsActivity::class.java)
            intent.putExtra(Constants.AROUTER_KEY_VIDEO_ID, id)
            intent.putExtra(Constants.AROUTER_KEY_VIDEO_NAME, name)
            intent.putExtra(Constants.AROUTER_KEY_VIDEO_PICTURE, pic)
            context.startActivity(intent)
        }
    }

    private lateinit var loadingView: LoadingView
    private lateinit var videoPlayer: MixPlayerView
    private lateinit var videoControlGroup: Group
    private lateinit var btnSourceSelect: View
    private lateinit var btnShare: View
    private lateinit var btnEpisodeSelect: View
    private lateinit var btnFavorite: View
    private lateinit var ivFavorite: ImageView
    private lateinit var tvSourceName: TextView

    private var videoId = -1L
    private var videoPic: String? = null
    private var videoName: String? = null
    private var isFullScreenModel = false



    // 显示视频线路dialog
    private var videoSourceDialog: VideoSourceDialog? = null
    // 显示剧集列表dialog
    private var videoEpisodeDialog: VideoEpisodeDialog? = null
    private val viewModel by lazy { getViewModel(VideoDetailViewModelNew::class.java) }

    override fun getLayoutResId(): Int {
        return R.layout.activity_video_player_skits
    }

    override fun initView() {
        super.initView()
//        videoPreGroup = findViewById(R.id.group_video_load_pre)
        loadingView = findViewById(R.id.player_loading)
        videoPlayer = findViewById(R.id.videoPlayer)
        videoControlGroup = findViewById(R.id.group_video_control)

        btnFavorite = findViewById(R.id.layout_video_favorite)
        btnShare = findViewById(R.id.layout_video_share)
        btnEpisodeSelect = findViewById(R.id.tv_video_episode_select)
        btnSourceSelect = findViewById(R.id.video_layout_source)

        ivFavorite = findViewById(R.id.iv_video_favorite)
        tvSourceName = findViewById(R.id.tv_video_source_name)


        // 显示加载状态
        loadingView.showLoading()

        videoPic = intent?.getStringExtra(Constants.AROUTER_KEY_VIDEO_PICTURE)
    }

    override fun bindEvent() {
        super.bindEvent()
//        videoPlayer.setOnControlViewStatusListener(object: OnControlViewStatusListener {
//            override fun onControlViewStatus(isDisplay: Boolean) {
//                videoControlGroup.visibility = if (isDisplay) {
//                    if (isFullScreenModel) {
//                        View.GONE
//                    } else {
//                        View.VISIBLE
//                    }
//                } else {
//                    View.GONE
//                }
//            }
//        })

        videoPlayer.setVodPreparedListener(object: OnPreparedListener {
            override fun onPrepared() {
                videoControlGroup.visibility = View.VISIBLE
                videoPlayer.start()
            }
        })

        videoPlayer.setFullScreenStatusListener(object: OnFullScreenStatusListener {
            override fun onFullScreen(isFullScreen: Boolean) {
                isFullScreenModel = isFullScreen
                // 控制是否可以录屏
                if (isFullScreenModel) {
                    videoControlGroup.visibility = View.GONE
                } else {
                    videoControlGroup.visibility = View.VISIBLE
                }
            }
        })

        videoPlayer.setVodCompleteListener(object : OnVodCompleteListener {
            override fun onVodComplete(): Boolean {
                // 默认是继续播放下一集
                val episodeList = viewModel.getCurrentSourceData()?.episodes?:return true
                val currentSource = episodeList.size
                val index = episodeList.indexOfFirst { it.isPlaying }
                // 播放到最后一集，无法再自动播放了
                return index >= currentSource - 1
            }
        })

        // 播放器切换剧集监听
        videoPlayer.setVodChangeEpisodeListener(object : OnChangeEpisodeListener {
            override fun onChangeEpisode(position: Int) {
                // 获取当前正在播放的剧集的position
                toPlayVideo(position)
            }

            override fun onPlayNext(): Boolean {
                val targetSource = viewModel.getCurrentSourceData()
                val episodeListSize = targetSource?.episodes?.size?:0
                if (viewModel.currentEpisodePosition >= episodeListSize - 1) { // 已经是最后一集
                    return false
                }
                val nextIndex = viewModel.currentEpisodePosition + 1
                toPlayVideo(nextIndex)
                return nextIndex < episodeListSize - 1
            }

            override fun showEpisodeList() {
            }

            override fun onPause() {
                updatePlayHistory()
            }
        })

        videoPlayer.setOnLoadUnlockAdListener(object : OnLoadUnlockAdListener {
            override fun onLoadUnlockAd() {
                videoPlayer.hideUnlockUI()
                // 加载广告
                viewModel.loadMultipleAd(this@VideoPlayerSkitsActivity, VideoDetailViewModelNew.AD_TYPE_UNLOCK) {
                    if (isActivityNotActive()) return@loadMultipleAd
                    // 修改当前剧集的解锁标签
                    viewModel.clearCurrentEpisodeUnlockAdTag()
                    // 修改当前剧集的解锁标签
                    val episodeList = viewModel.getCurrentSourceData()?.episodes
                    if (episodeList.isNullOrEmpty()) return@loadMultipleAd
                    val currentEpisode = episodeList.get(viewModel.currentEpisodePosition)
                    playVideo(currentEpisode.url?:"", currentEpisode.title, episodeList.size)
                }
            }
        })

        btnFavorite.setOnClickListener(this)
        btnShare.setOnClickListener(this)
        btnEpisodeSelect.setOnClickListener(this)
        btnSourceSelect.setOnClickListener(this)
    }

    override fun init(savedInstanceState: Bundle?) {
        videoId = intent?.getLongExtra(Constants.AROUTER_KEY_VIDEO_ID, -1L)?:-1L
        videoName = intent?.getStringExtra(Constants.AROUTER_KEY_VIDEO_NAME)
        if (videoId <= 0) {
            showVideoFailureDialog()
            return
        }
        doHttpVideoDetail()
    }

    private fun doHttpVideoDetail() {
        viewModel.getVideoDetail(videoId, object: OnRetrofitResultListener<VideoEntity>{
            override fun onSuccess(t: VideoEntity) {
                if (isActivityNotActive()) return
                val favoriteResId = if (t.isFavorite) R.drawable.ic_video_favorited else R.drawable.ic_favorite
                ivFavorite.setBackgroundResource(favoriteResId)

                val firstSource = t.sourcePlayList?.firstOrNull()
                tvSourceName.text = AppUtils.getSourceName(firstSource?.id?:0)

                val episode = firstSource?.episodes?.firstOrNull()
                val size = firstSource?.episodes?.size?:0


                loadingView.hideLoading()
                playVideo(episode?.url?:"", episode?.title, size)
                LogC.e("播放地址: " + episode?.url)
                loadInterstitialAd()
            }

            override fun onFailed(msg: String) {
                if (isActivityNotActive()) return
                loadingView.hideLoading()
                showErrorDialog("视频信息请求失败，请重试！", getString(R.string.retry), {
                    loadingView.showLoading()
                    loadingView.postDelayed({
                        doHttpVideoDetail()
                    }, 1000)
                })
            }
        })
    }

    // 提示当前视频已经失效
    private fun showVideoFailureDialog() {
        showErrorDialog("当前视频已失效，请返回！", "返回", {
            finish()
        })
    }

    override fun onNoDoubleClick(v: View?) {
        super.onNoDoubleClick(v)
        when(v){
            btnFavorite -> {
                val isFavorite = viewModel.switchFavoriteStatus(videoId)
                val favoriteResId = if (isFavorite) R.drawable.ic_video_favorited else R.drawable.ic_favorite
                ivFavorite.setBackgroundResource(favoriteResId)
            }

            btnShare -> AppUtils.shareApp(this)

            btnEpisodeSelect -> showEpisodeDialog()

            btnSourceSelect -> showVideoSourceDialog()
        }
    }


    // 显示视频线路选择弹窗
    private fun showVideoSourceDialog() {
        val videoDetail = viewModel.videoDetailModel ?: return
        if (videoSourceDialog == null) {
            videoSourceDialog = VideoSourceDialog(this)
            videoSourceDialog?.setVideoSourceClickListener(object : VideoSourceDialog.OnVideoSourceClickListener {
                override fun onSourceClicked(source: PlayInfoResponse) {
                    viewModel.currentSourceId = source.id
                    // 设置当前的线路的名称
                    tvSourceName.text = AppUtils.getSourceName(source.id)

                    toPlayVideo(viewModel.currentEpisodePosition, false)
                }

                override fun onSourceResorted() {

                }
            })
        }
        // 设置当前的线路纤细
        videoSourceDialog?.setVideoSource(videoDetail.id, viewModel.currentSourceId, videoDetail.sourcePlayList)
        videoSourceDialog?.show()
    }

    // 显示剧集列表
    private fun showEpisodeDialog() {
        val videoDetail = viewModel.videoDetailModel ?: return
        if (videoEpisodeDialog == null) {
            videoEpisodeDialog = VideoEpisodeDialog(this)
            videoEpisodeDialog?.setEpisodeClickCallback(object : OnEpisodeClickCallback {
                override fun onEpisodeClick(oldPos: Int, newPos: Int, isChangeEpisode: Boolean) {
                    val currentPosition = videoPlayer.getCurrentPosition()
                    if (currentPosition > 500) { // 忽略加载未成功的剧集切换
                        updatePlayHistory()
                    }
                    toPlayVideo(newPos)
                }

            })
        }


        videoEpisodeDialog?.setEpisodes(
            videoDetail.id,
            Constants.VIDEO_CATEGORY_ALBUM,
            videoDetail.sourcePlayList?.firstOrNull { viewModel.currentSourceId == it.id}?.episodes
        )
        videoEpisodeDialog?.show()
        return
    }

    // 更新历史记录
    private fun updatePlayHistory() {
        val duration = videoPlayer.getDuration()
        val currentPosition = videoPlayer.getCurrentPosition()
        val historyPos = if (currentPosition >= duration - 5) {
            duration - 5
        } else currentPosition
        viewModel.updateVideoHistory(historyPos)
    }


    private fun toPlayVideo(position: Int, isLoadAd: Boolean = true){
        val targetSource = viewModel.getCurrentSourceData()
        val episodeList = targetSource?.episodes
        val size = episodeList?.size?:0
        val episode = episodeList?.get(position)
        if (episode == null) {
            showErrorDialog("当前剧集无法播放，请尝试切换其他线路！", yes = getString(R.string.confirm), yesClickListener = {
                hideErrorDialog()
            })
            return
        }
        viewModel.currentEpisodePosition = position
        videoPlayer.onVodStop()
        LogC.e("播放地址: " + episode.url)
        playVideo(episode.url?:"", episode.title, size)
        if (isLoadAd) {
            loadInterstitialAd(true)
        }
    }
    private fun playVideo(url: String, title: String?, episodeCount: Int){

        val videoUrl = if (BuildConfig.DEBUG) {
            "https://vip.kuaikan-play1.com/20240430/3xPdowaa/index.m3u8"
        } else {
            url
        }

        videoPlayer.playVideo(
            // 播放url
            url = videoUrl,
            title = "$videoName  $title",
            // 跳转进度
            startPosition = viewModel.currentPlayStartPosition,
            currentPlayIndex = viewModel.currentEpisodePosition,
            episodeSize = episodeCount
        )
    }

    override fun onPause() {
        super.onPause()
        // 先保存历史记录
        updatePlayHistory()
    }

    // 加载插页广告
    private fun loadInterstitialAd(isCheckUnlockAd: Boolean = false) {
        if (isCheckUnlockAd) { // 如果当前视频需要解锁，则不在加载插屏广告
            val episode = viewModel.getCurrentEpisode()
            if (episode?.isLockVideoAd == true) return
        }
        VideoInterstitialAdTools.loadAd(this, object : OnLoadAdCallback() {
            override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                super.onAdLoaded(ad, *tag)
                if (isActivityNotActive()) return
                LogC.e("newShowStyle -> 显示广告...")
                videoPlayer.pause()
                videoPlayer.postDelayed({
                    if (isActivityNotActive()) return@postDelayed
                    VideoInterstitialAdTools.showAd(this@VideoPlayerSkitsActivity)
                }, 500)

            }

            override fun onAdLoadFailed(errorCode: Int) {
                super.onAdLoadFailed(errorCode)
                LogC.e("newShowStyle -> 有广告缓存，并且没有广告展示, 但是出现错误...$errorCode")
                if (isActivityNotActive()) return
                // 开始播放视频
                videoPlayer.start()
            }

            override fun onAdComplete() {
                super.onAdComplete()
                if (isActivityNotActive()) return
                LogC.e("newShowStyle -> 广告展示完成...")
                // 开始播放视频
                videoPlayer.start()
            }
        })
    }
}